import { requestWithErrorHandling } from "./request";

// 获取阅读量Top10文章
export function fetchTop10Articles() {
  return requestWithErrorHandling({
    url: "/analyze/top10",
    method: "get",
    params: { t: Date.now() }, // 添加时间戳禁用缓存
    errorMessage: "获取Top10文章失败",
  }).then((res) => {
    if (res.code === 1 && res.data && Array.isArray(res.data.list)) {
      return res.data.list.map((item) => ({
        ...item,
        tags: item.tags ? item.tags.split(",") : [],
        username: item.username || item.user_id || "未知",
        create_at: item.create_at,
        update_at: item.update_at,
      }));
    }
    return [];
  });
}

// 获取统计数据
export function fetchStatistics() {
  return requestWithErrorHandling({
    url: "/analyze/statistics",
    method: "get",
    params: { t: Date.now() }, // 添加时间戳禁用缓存
    errorMessage: "获取统计数据失败",
  }).then((res) => {
    if (res.code === 1 && res.data) {
      return {
        totalViews: res.data.total_views || 0,
        totalArticles: res.data.total_articles || 0,
        totalUsers: res.data.active_authors || 0,
        avgViews: res.data.average_views || 0,
      };
    }
    return {
      totalViews: 0,
      totalArticles: 0,
      totalUsers: 0,
      avgViews: 0,
    };
  });
}

// 获取词云图片url
export function fetchWordCloudUrl() {
  return requestWithErrorHandling({
    url: "/analyze/wordcloud",
    method: "post",
    params: { t: Date.now() }, // 添加时间戳禁用缓存
    errorMessage: "获取词云图片失败",
  }).then((res) => {
    if (res.code === 1 && res.data) {
      return res.data;
    }
    return "";
  });
}

// 获取按分类统计的文章数据
export function fetchArticleCountByCategory() {
  return requestWithErrorHandling({
    url: "/analyze/article-count-by-category",
    method: "get",
    params: { t: Date.now() }, // 添加时间戳禁用缓存
    errorMessage: "获取分类统计数据失败",
  }).then((res) => {
    if (res.code === 1 && res.data) {
      return res.data.list || [];
    }
    return [];
  });
}

// 获取按月度发布的文章数据
export function fetchMonthlyPublishCount() {
  return requestWithErrorHandling({
    url: "/analyze/monthly-publish-count",
    method: "get",
    params: { t: Date.now() }, // 添加时间戳禁用缓存
    errorMessage: "获取月度发布数据失败",
  }).then((res) => {
    if (res.code === 1 && res.data) {
      return res.data.list || [];
    }
    return [];
  });
}
